package org.dromara.pay.gn.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.dromara.pay.common.payAlipayConfig;

import org.dromara.pay.crud.service.IPayActivityRegistrationCrudService;
import org.dromara.pay.crud.service.IPayAlipayOrdersSignCrudService;
import org.dromara.pay.domain.PayActivityOrder;
import org.dromara.pay.domain.bo.PayActivityOrderBo;
import org.dromara.pay.domain.bo.PayActivityRegistrationBo;
import org.dromara.pay.domain.bo.PayAlipayOrdersSignBo;
import org.dromara.pay.mapper.PayActivityOrderMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Map;

/**
 * pay-支付
 *
 * @author yf
 * @date 2024-06-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/pay")
public class payAliPayController {

    /**
     * 每次请求都需换端口
     * http://127.0.0.1:9098/pay/alipay?subject=%E5%A4%A7%E4%BC%9A%E6%8A%A5%E5%90%8D&orderId=148&totalAmount=10
     * wtcgwr4104@sandbox.com 商户账号
     * 111111
     * nenuun4733@sandbox.com 买家账号
     * 111111
     *
     * 流程调试
     * 改订单id，改订单对于的注册id的状态
     * */
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";


    private final IPayActivityRegistrationCrudService registrationService;



    private final PayActivityOrderMapper activityOrderMapper;

    private final IPayAlipayOrdersSignCrudService alipayOrdersSignService;

    @Autowired
    private payAlipayConfig aliPayConfig;
    @GetMapping("/alipay")
    public void pay(PayActivityOrderBo aliPay, HttpServletResponse httpResponse) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", aliPay.getOrderId());  // 我们自己生成的订单编号
        bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额
        bizContent.set("subject", aliPay.getSubject());   // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/notify") // 注意这里必须是POST接口
    public ResponseEntity<String> payNotify(HttpServletRequest request) throws Exception {
        // 1. 验签
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
            // System.out.println(name + " = " + request.getParameter(name));
        }

        if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
            System.out.println("=========支付宝异步回调========");

            String outTradeNo = params.get("out_trade_no");
            String alipayTradeNo = params.get("trade_no");

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8");

            if (checkSignature) {
                PayAlipayOrdersSignBo payAlipayOrdersSignBo = new PayAlipayOrdersSignBo();
                payAlipayOrdersSignBo.setSubject(params.get("subject"));
                payAlipayOrdersSignBo.setAlipayNo(alipayTradeNo);
//                payAlipayOrdersSignBo.setGmtPaymentFromString(params.get("gmt_payment"));
                payAlipayOrdersSignBo.setTradeStatus(params.get("trade_status"));
                payAlipayOrdersSignBo.setAlipayId(params.get("trade_no"));
                payAlipayOrdersSignBo.setBuyer(params.get("buyer_id"));
//                payAlipayOrdersSignBo.setTotalAmountFromString(params.get("total_amount"));
//                payAlipayOrdersSignBo.setBuyerPayAmountFromString(params.get("buyer_pay_amount"));
                alipayOrdersSignService.insertByBo(payAlipayOrdersSignBo);

                // 更改报名状态
                PayActivityOrder payActivityOrder = activityOrderMapper.selectById(Integer.parseInt(outTradeNo));
                Integer activityRegistrationId = payActivityOrder.getActivityRegistrationId();

                PayActivityRegistrationBo registrationBo = new PayActivityRegistrationBo();
                registrationBo.setRegistrationId(activityRegistrationId);
                registrationBo.setRegistrationStatus("3");
                registrationService.updateByBo(registrationBo);

            }
        }
        return ResponseEntity.ok("success");
    }
}


